<script lang="ts" setup>
import type {
  TextInputAppearance,
  TextInputControlSize,
  TextInputType,
} from '@fluentui/web-components';

withDefaults(
  defineProps<{
    appearance?: TextInputAppearance;
    autocomplete?: string;
    autofocus?: boolean;
    controlSize?: TextInputControlSize;
    disabled?: boolean;
    elementId?: string;
    maxlength?: number;
    minlength?: number;
    multiple?: boolean;
    name?: string;
    pattern?: string;
    placeholder?: string;
    readonly?: boolean;
    required?: boolean;
    size?: number;
    spellcheck?: boolean;
    type?: TextInputType;
    // value prop removed as it's now handled by defineModel
  }>(),
  {
    appearance: 'outline',
    autofocus: false,
    controlSize: 'medium',
    disabled: false,
    multiple: false,
    readonly: false,
    required: false,
    spellcheck: false,
    type: 'text',
    autocomplete: undefined,
    maxlength: undefined,
    minlength: undefined,
    name: undefined,
    pattern: undefined,
    placeholder: undefined,
    size: undefined,
    elementId: undefined,
  },
);

const emit = defineEmits<{
  blur: [event: FocusEvent];
  change: [event: Event];
  focus: [event: FocusEvent];
  input: [event: Event];
  // update:value emission is removed as it's handled by defineModel
}>();

// Define the model with 'value' as argument
const value = defineModel<string>({ default: '' });
const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  emit('input', event);
  // Update the model directly instead of emitting an event
  value.value = target.value;
};

const handleChange = (event: Event) => {
  emit('change', event);
};

const handleFocus = (event: FocusEvent) => {
  emit('focus', event);
};

const handleBlur = (event: FocusEvent) => {
  emit('blur', event);
};
const textInput = ref<HTMLInputElement>();
onMounted(() => {
  nextTick(() => {
    if (textInput.value) {
      // Set the initial value from the model
      textInput.value.value = value.value;
    }
  });
});
</script>

<template>
  <fluent-text-input
    ref="textInput"
    :appearance="appearance"
    :autocomplete="autocomplete"
    :autofocus="autofocus"
    :control-size="controlSize"
    :disabled="disabled"
    :maxlength="maxlength"
    :minlength="minlength"
    :multiple="multiple"
    :name="name"
    :pattern="pattern"
    :placeholder="placeholder"
    :readonly="readonly"
    :required="required"
    :size="size"
    :spellcheck="spellcheck"
    :type="type"
    :value="value"
    :id="elementId"
    @input="handleInput"
    @change="handleChange"
    @focus="handleFocus"
    @blur="handleBlur"
  >
    <slot></slot>
  </fluent-text-input>
</template>

<style scoped></style>
